import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate"; // 持久化存储插件

import user from "./modules/user";
import study from "./modules/study";

Vue.use(Vuex);

const store = new Vuex.Store({
  plugins: [
    createPersistedState({
      storage: window.sessionStorage,
      reducer: () => {
        return {
          user: {},
        };
      },
    }),
  ],
  state: {
    current: Date.now(), // 当前时间
    intervalID: 0,
    screenLoading: false, // 显示全屏加载中
  },
  getters: {
    hidden() {
      if (typeof document.hasFocus !== "function") {
        return document.hidden;
      }
      return !document.hasFocus();
    },
  },
  mutations: {
    startComputeCurrent(state) {
      state.intervalID = setInterval(() => {
        state.current = Date.now();
      }, 500);
    },
    stopComputeCurrent(state) {
      clearInterval(state.intervalID);
      state.intervalID = 0;
    },
    toggleLoading(state, value) {
      state.screenLoading = value;
    },
    updateItem(state, { field, value }) {
      state[field] = value;
    },
  },
  modules: {
    user,
    study,
  },
});

export default store